package implementations;

import java.util.concurrent.Delayed;
import java.util.concurrent.TimeUnit;

/**
 * Wrapper class for connection that helps to use DelayedQueue
 * @param <T>
 */
class MyConnectionSource<T> implements Delayed {

    private T connection;
    private long startTime;

    public MyConnectionSource(T connection, long delay, TimeUnit unit) {
        this.connection = connection;
        startTime = System.currentTimeMillis() + delay;
    }

    public T getConnection() {
        return connection;
    }

    @Override
    public long getDelay(TimeUnit unit) {
        long diff = startTime - System.currentTimeMillis();
        return unit.convert(diff, TimeUnit.MILLISECONDS);
    }

    @Override
    public int compareTo(Delayed o) {
        if (this.startTime < ((MyConnectionSource) o).startTime) {
            return -1;
        }
        if (this.startTime > ((MyConnectionSource) o).startTime) {
            return 1;
        }
        return 0;
    }
}
